<template>

  <span style="color: #ff0000; font-weight: 700">{{ hour }}：{{ min }}：{{ sec }}</span>

</template>

<script setup  name="ExamTimer">
import { nextTick, onBeforeMount } from "vue";

const emits = defineEmits(['timeout']);

/**属性传值 */
const props = defineProps({
  timeValue: {
    type: Number,
    default: 0
  },
})
const leftSeconds = ref(0)
const hour = ref('00')
const min = ref('00')
const sec = ref('00')
// 设置初始化
onBeforeMount(() => {
  leftSeconds.value = props.timeValue
});

watch(
	() => props.timeValue,
	(newValue, oldValue) => {
    leftSeconds.value = props.timeValue
    nextTick(()=>{
      countdown()
    })
	},{ deep: true, immediate: true });

// 进行倒计时
const countdown = () => {

  // 倒计时结束了
  if (leftSeconds.value < 0) {
    emits('timeout');
    return
  }
  // 时
  const hourNum = parseInt(leftSeconds.value / 3600)
  const minNum = parseInt(leftSeconds.value / 60)
  const secNum = parseInt(leftSeconds.value % 60)

  hour.value = hourNum > 9 ? hourNum : '0' + hourNum
  min.value = minNum > 9 ? minNum : '0' + minNum
  sec.value = secNum > 9 ? secNum : '0' + secNum
  leftSeconds.value -= 1

  setTimeout(function () {
    countdown()
  }, 1000)
}

</script>

